package com.android.kotlincoroutinemvvmdemo.view

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.ViewGroup
import androidx.core.view.get
import com.android.kotlincoroutinemvvmdemo.R

class TopContentViewGroup @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null
) : ViewGroup(context, attributeSet) {

    private var totalMoveX = 0
    private var downX = 0

    init {
        addView(
            inflate(context, R.layout.layout01, null),
            MarginLayoutParams(MarginLayoutParams.MATCH_PARENT, MarginLayoutParams.WRAP_CONTENT)
        )

        addView(
            inflate(context, R.layout.layout02, null),
            MarginLayoutParams(MarginLayoutParams.MATCH_PARENT, MarginLayoutParams.WRAP_CONTENT)
        )
    }


    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        for (i in 0.until(childCount)) {
            val child = get(i)
            val childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
                MeasureSpec.getSize(heightMeasureSpec),
                MeasureSpec.UNSPECIFIED
            )
            child.measure(widthMeasureSpec, childHeightMeasureSpec)
        }
    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        var offsetX = 0
        for (i in 0.until(childCount)) {
            val child = get(i)
            val childWidth = child.measuredWidth
            val childHeight = child.measuredHeight
            child.layout(offsetX, 0, childWidth + offsetX, childHeight)
            offsetX += childWidth
        }
    }

    override fun generateLayoutParams(attrs: AttributeSet?): LayoutParams {
        return MarginLayoutParams(context, attrs)
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        performClick()
        when (event?.action) {
            MotionEvent.ACTION_DOWN -> {
                downX = event.x.toInt()
            }
            MotionEvent.ACTION_MOVE -> {
                val moveX = event.x.toInt()
                totalMoveX += (moveX - downX)
                scrollTo(-totalMoveX, 0)
                downX = moveX
            }
            MotionEvent.ACTION_UP -> {

            }
        }
        return true
    }

    override fun performClick(): Boolean {
        return super.performClick()
    }
}